package com.rongxue.controller.index;

import com.alibaba.fastjson.JSONObject;
import com.rongxue.mapper.*;
import com.rongxue.pojo.*;
import com.rongxue.service.Impl.CashInAndOutServiceImpl;
import com.rongxue.service.SuserService;
import com.rongxue.service.UserAccountService;
import com.rongxue.service.ProjectService;
import com.rongxue.service.shanbei.services.AccountService;
import com.rongxue.service.shanbei.util.ConfigUtil;
import com.rongxue.utils.CommonUtils;
import com.rongxue.utils.DateUtil;
import com.rongxue.utils.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by yangweijian on 2018/1/17.
 */
@Controller
public class UserController {

    @Autowired
    private UserAccountService userAccountService;

    @Autowired
    private SuserService suserService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private SUserMapper sUserMapper;

    @Autowired
    private SIntegralMapper sIntegralMapper;

    @Autowired
    private SProjectMapper sProjectMapper;

    @Autowired
    private SInvestmentDetailMapper sInvestmentDetailMapper;
    @Autowired
    private SUserAccountMapper sUserAccountMapper;
    /**
     * 用户资金
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/user/account_general")
    @ResponseBody
    public ObjectResult account_general(XMLBean xmlBean){
        if(xmlBean.getToken()!=null) {
            String userId = CommonUtils.decToken(xmlBean.getToken());
            SUserAccount userAccount = userAccountService.selectUserAccountByUid(Long.parseLong(userId));
            SUser sUser = sUserMapper.selectByPrimaryKey(Long.parseLong(userId));


            userAccount.setTotal_due_capital(sInvestmentDetailMapper.selectTotalDueCapital(userId));
            if(userAccount==null) return ObjectResult.build("0","用户Id为空");


            if(sUser.getCard_no2()!=null&&!"".equals(sUser.getCard_no2())) {
                String str = null;
                Map<String, Object> reqMap = new HashMap<String, Object>();
                reqMap.put("service", "account_balance");
                reqMap.put("card_no", sUser.getCard_no2());
                reqMap.put("customer_no", sUser.getCustomer_no());
                reqMap.put("timestamp", String.valueOf(new Date().getTime() / 1000));
                reqMap.put("uuid", "" + System.currentTimeMillis() / 100);
                reqMap.put("sign_type", "");
                reqMap.put("encode", "UTF-8");
                reqMap.put("version", "2.0.0");
                reqMap.put("custom", "");
                reqMap.put("client", "000001");
                reqMap.put("client_ip", "47.98.107.188");
                reqMap.put("client_service", "00:16:3e:11:b0:02");
                String rft_key = ConfigUtil.getPro("bank.key");
                String rft_secret = ConfigUtil.getPro("bank.secret");
                str = AccountService.createAccount(reqMap, rft_key, rft_secret);
                JSONObject jsonObject = JSONObject.parseObject(str);
                BigDecimal amount =userAccount.getAccount_able();

                userAccount.setWalletTotle(new BigDecimal(jsonObject.getString("balance")));
                userAccount.setAccount_able(new BigDecimal(jsonObject.getString("balance")));
                //如果余额与陕坝不一致修改余额
                if (amount.compareTo(userAccount.getAccount_able())!=0){
                    sUserAccountMapper.updateByPrimaryKeySelective(userAccount);
                }
            }

            if(sUser.getType()==2 || sUser.getType() == 3){
                userAccount.setAccount_total(userAccount.getAccount_able());
            }else {
                userAccount.setAccount_total(userAccount.getAccount_able().add(userAccount.getWait_amount()));
            }
            userAccount.setTotalInvestInterest(userAccount.getTotalInvestInterest().setScale(2));

//            userAccount.setService_phone("客服电话：申请中");
//            userAccount.setService_time("工作时间：9:00 - 18:00");
            return ObjectResult.build("1","成功",userAccount);
        }
        else {
            return ObjectResult.build("0","token不存在");
        }
    }

    /**
     * 用户优惠列表
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/user/award_list", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult award_list(XMLBean xmlBean){
        Map<String,Object> data = new HashMap<String,Object>();
        if(xmlBean.getToken()!=null||!"".equals(xmlBean.getToken())) {
            String userId = CommonUtils.decToken(xmlBean.getToken());
            if(userId==null||userId.equals("")) return ObjectResult.build("0","用户Id为空");
            List<Rewards> list = new ArrayList<Rewards>();
            if(xmlBean.getType()==1) {
                suserService.updateRedpacketByUserId(userId);
               list = suserService.selectRedpacketByUserId(userId);
            }
            else if(xmlBean.getType()==2){
                suserService.updateInterestcouponByUserId(userId);
                list = suserService.selectInterestcouponByUserId(userId);
            }
            else if(xmlBean.getType()==3){
                suserService.updateCashcouponByUserId(userId);
                list = suserService.selectCashcouponByUserId(userId);
            }
            else{
                return ObjectResult.build("0","传递type有误");
            }
            Page<Rewards> page = new Page<>();
            page.setP(xmlBean.getP());
            page.setPageSize(10d);
            List<Rewards> content = page.getPageContent(list);
            data.put("list",content);
            data.put("count",page.getPageTotal());
            return  ObjectResult.build("1","成功",data);
        }
        else {
            return ObjectResult.build("0","token不存在");
        }
    }

    /**
     * 用户投资记录
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/user/user_invest")
    @ResponseBody
    public ObjectResult user_invest(XMLBean xmlBean){
        if(xmlBean.getToken()==null||xmlBean.getToken().equals(""))  return ObjectResult.build("0","token不存在");
        String userId = CommonUtils.decToken(xmlBean.getToken());
        if(userId==null||userId.equals("")) return ObjectResult.build("0","用户Id为空");
        Map<String,Object> map = new HashMap<String,Object>();
        Map<String,Object> data = new HashMap<String,Object>();
        map.put("userId",userId);
        if(xmlBean.getStatus()==4){
            map.put("status",2);
        }
        if(xmlBean.getStatus()==2){
            map.put("status",1);
        }

        List<SProject> list = projectService.selectUserInvestList(map);
        Page<SProject> page = new Page<>();
        page.setP(xmlBean.getP());
        page.setPageSize(10);
        List<SProject> content = page.getPageContent(list);

        for (SProject sProject :content){
            sProject.setAdd_time(sProject.getAdd_time().substring(0,sProject.getAdd_time().lastIndexOf(".")));
            //sProject.setContract_url("http://admin.guangshizc.com"+sProject.getContract_url());
//            sProject.setEnd_time(sProject.getEnd_time().substring(0,sProject.getEnd_time().lastIndexOf(".")));
            sProject.setStart_time(sProject.getStart_time().substring(0,sProject.getStart_time().lastIndexOf(".")));
            if(new Date().compareTo(DateUtil.parseDateTime(sProject.getStart_time()))<0){
                sProject.setState("加入计划");
            }
            if(new Date().compareTo(DateUtil.parseDateTime(sProject.getStart_time()))>=0){
                sProject.setState("生息中");
            }
            if(sProject.getStatus()==2){
                sProject.setState("已结束");
            }
            sProject.setAccrual2(sProject.getAccrual().toString());
        }
        data.put("list",content);
        data.put("count",page.getPageTotal());
        return ObjectResult.build("1","成功",data);
    }


    /**
     * 投资详情
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/user/investment_details", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult investment_details(XMLBean xmlBean){
        if(xmlBean.getToken()==null||xmlBean.getToken().equals(""))  return ObjectResult.build("0","token不存在");
        SProject sProject = sProjectMapper.selectInvestmentDetails(xmlBean.getId());
        int repayment_day = DateUtil.getDaysBetweenToDate(sProject.getEnd_time(), new Date());
        if(repayment_day<0){
            repayment_day=0;
        }
        sProject.setRepayment_day(repayment_day);
        sProject.setUrl("");
        return ObjectResult.build("1","成功",sProject);
    }


    /**
     * 签到
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/user/sing_in", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult sing_in(XMLBean xmlBean){
        if(xmlBean.getToken()==null||xmlBean.getToken().equals(""))  return ObjectResult.build("0","token不存在");
        ObjectResult objectResult = suserService.insertToSing_in(xmlBean);
        return objectResult;
    }

    /**
     * 签到列表
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/user/sing_list", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult sing_list(XMLBean xmlBean){
        if(xmlBean.getToken()==null||xmlBean.getToken().equals(""))  return ObjectResult.build("0","token不存在");
        ObjectResult objectResult = suserService.selectToSing_list(xmlBean);
        return objectResult;
    }

    /**
     * 邀请人列表
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/user/invite", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult invite(XMLBean xmlBean) throws IOException {
        Map<String,Object> data = new HashMap<String,Object>();
        if(xmlBean.getToken()==null||xmlBean.getToken().equals(""))  return ObjectResult.build("0","token不存在");
        String userId = CommonUtils.decToken(xmlBean.getToken());
        if(userId==null||userId.equals("")) return ObjectResult.build("0","用户Id为空");
        List<SUser> list = sUserMapper.selectInviteListByUserId(Integer.parseInt(userId));
        Page<SUser> page = new Page<>();
        page.setP(xmlBean.getP());
        page.setPageSize(10);
        List<SUser> content = page.getPageContent(list);
        for (SUser s:content){
            s.setAdd_time(s.getAdd_time().substring(0,s.getAdd_time().lastIndexOf(".")));
        }
        data.put("userId",userId);
        SUser user = suserService.selectUserByMap(data);
        data.clear();

        data.put("title","送你938元大红包，快来老爷客一起赚收益吧！");
        data.put("content","老爷客，会赚钱的人都来了，现在下载立即享受新手18%年化收益率，更有938元大红包等你拿！");

        data.put("list",content);
        data.put("count",page.getPageTotal());
        data.put("url",CashInAndOutServiceImpl.PAGE_NOTIFY_URL+"index/regist?invite="+user.getInvite()+"&&channel="+user.getChannel());
        data.put("invite",user.getInvite());
        return ObjectResult.build("1","成功",data);
    }

    /**
     * 积分列表
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/user/integral_list", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
        public ObjectResult integral_list(XMLBean xmlBean){
        Map<String,Object> data = new HashMap<String,Object>();
        if(xmlBean.getToken()==null||xmlBean.getToken().equals(""))  return ObjectResult.build("0","token不存在");
        String userId = CommonUtils.decToken(xmlBean.getToken());

        List<SIntegral> integrals = sIntegralMapper.selectIntegralByUserId(userId);
        Page<SIntegral> page = new Page<>();
        page.setP(xmlBean.getP()==null? 1:xmlBean.getP());
        page.setPageSize(10);
        List<SIntegral> content = page.getPageContent(integrals);
        for (SIntegral s:content){
            s.setAddTime(s.getAddTime().substring(0,s.getAddTime().lastIndexOf(".")));
            switch (s.getType()){
                case 0:
                    s.setTitle("签到");break;
                case 1:
                    s.setTitle("邀请好友");break;
                case 2:
                    s.setTitle("投资");break;
                case 3:
                    s.setTitle("抽奖");break;
                case 4:
                    s.setTitle("积分兑换");break;
                default:
                    break;
            }
        }
        data.put("userId",userId);
        SUser sUser = suserService.selectUserByMap(data);
        data.clear();
        data.put("list",content);
        data.put("integral",sUser.getIntegral());
        data.put("count",page.getPageTotal());

        return ObjectResult.build("1","成功",data);
    }

    /**
     * 个人积分
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/user/integral", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult integral(XMLBean xmlBean){
        Map<String,Object> data = new HashMap<String,Object>();
        if(xmlBean.getToken()==null||xmlBean.getToken().equals(""))  return ObjectResult.build("0","token不存在");
        String userId = CommonUtils.decToken(xmlBean.getToken());

        data.put("userId",userId);
        SUser sUser = suserService.selectUserByMap(data);
        data.clear();
        data.put("integral",sUser.getIntegral());
        data.put("rule","兑换1%加息券需要消耗1000积分，兑换成功之后加息券将会发放到您的奖励中。 积分不会有时间限制，但是兑换为加息券后，加息券会有使用期限，请尽快使用，以免逾期作废");

        return ObjectResult.build("1","成功",data);
    }

    /**
     * 积分兑换加息券
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/user/integral_conversion")
    @ResponseBody
    public ObjectResult gold_conversion(XMLBean xmlBean){
        if(xmlBean.getToken()==null||xmlBean.getToken().equals(""))  return ObjectResult.build("0","token不存在");
        ObjectResult objectResult = new ObjectResult();
        try {
            objectResult = suserService.insertGold_conversion(xmlBean);
        }
        catch (Exception e){
            e.printStackTrace();
            return ObjectResult.build("0","失败");
        }
        return objectResult;
    }


    /**
     * 积分抽奖
     * @param xmlBean
     * @return
     */
//    @RequestMapping(value = "/user/lotte", method = RequestMethod.POST, produces = "application/json")
//    @ResponseBody
//    public ObjectResult lotte(XMLBean xmlBean){
//        ObjectResult objectResult = new ObjectResult();
//        try {
//             objectResult = suserService.insertLotteRule(xmlBean);
//        }catch (Exception e){
//            e.printStackTrace();
//            return  ObjectResult.build("0","失败");
//        }
//        return objectResult;
//    }

    /**
     * 领取体验金
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/user/experience", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult experience(XMLBean xmlBean){
        ObjectResult objectResult = new ObjectResult();
        try {
            objectResult = suserService.insertExperience(xmlBean);
        }catch (Exception e){
            e.printStackTrace();
            return  ObjectResult.build("0","失败");
        }
        return objectResult;
    }

    /**
     * 是否有体验金
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/user/have_experience", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult have_experience(XMLBean xmlBean) {
        return suserService.selectExperienceByUserId(xmlBean);

    }

    /**
     * 回款清单
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/user/back", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult back(XMLBean xmlBean){
        return suserService.back(xmlBean);
    }

    /**
     *  用户资金记录
     * @param xmlBean
     * @return
     */
    @RequestMapping(value = "/user/capital_record", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ObjectResult capital_record(XMLBean xmlBean){
        return userAccountService.selectWalletRecords(xmlBean);
    }
}
